package com.wd.cloud.applet.common.filter;

import com.wd.cloud.applet.common.Response;
import com.wd.cloud.applet.common.exception.CustomException;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author hjx
 */
@Component
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ResponseEntity handleException(HttpRequestMethodNotSupportedException e) { ;
        return Response.errorToRe(401, "不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity notFount(RuntimeException e) {
        return Response.errorToRe(501, ":" + e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e) {
        return Response.errorToRe(500, "网络异常，请稍后重试");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(CustomException.class)
    public ResponseEntity businessException(CustomException e) {
        return Response.errorToRe(e.getCode(), e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity validatedBindException(BindException e) {
        List<ObjectError> objectErrorList = e.getBindingResult().getAllErrors();
        StringBuilder message = new StringBuilder();
        for (ObjectError error : objectErrorList) {
            message.append(error.getDefaultMessage()).append(" & ");
        }
        return Response.errorToRe(301, message.substring(0, message.length() - 3));
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        StringBuilder message = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            message.append(fieldError.getDefaultMessage()).append(" & ");
        }
        return Response.errorToRe(302, message.substring(0, message.length() - 3));
    }
}
